"""
CPEM Plugins (lib/plugins.py)   
Copyright 2010, C.J. Steele, all rights reserved.

C.J. Steele <coreyjsteele@gmail.com>

This file contains the voodoo to make our plugins play in our XML/RPC 
server.  While what it accomplishes is fairly straight-forward, there 
are a couple of key points: 
1) all functions registered by a plugin will be called by clients using 
a name of "Plugin_Function", where "Plugin" is the base file-name of 
the plugin, and Function is the routine to be executed.  This is 
enforced here, and will help prevent name-space collissions. 
2) all plugins will be limited in regards to what registry values they 
can access, as well as prevented from running a muck in the other areas 
of the framework.
3) plugins will be provided a means by which they can interact with
users via a web-based interface (think Django.)
"""


import imp,pkgutil,os,sys,types

def get_functions(module):
    functionList = []
    for key,value in module.__dict__.items():
        if type(value) is types.FunctionType:
            functionList.append(value)
    return functionList


#TODO: CJS 8/12/2010 - review this, its hideous right now.  
def init_plugins(CPEM_Server,path='%s/plugins/' % (os.getcwd())):
    """init_plugins( CPEMSERVER, PATH )
    handles initializing plugins; i.e. finding them in the plugins directory, 
    and registering them with our RPC server.
    """
    sys.path.append(path)
    for loader,packageName,ispkg in pkgutil.iter_modules([ path ]):
        try:
            f,filename,description = imp.find_module(packageName)
            #print 'D: f="%s", filename="%s" and description="%s"' % ( f, filename, description )
            try:
                loaded = imp.load_module(packageName,f,filename,description)
                try:
                    for f in get_functions(loaded):
                        if f.__name__ is 'init':
                            # this is the initialization routine for the plugin, execute it
                            print('I: hit init in %s' % (packageName))
                            pass
                        elif f.__name__ is 'schedule':
                            # this is the special routine for the plugin to register scheduled events.
                            print('I: hit scheduler in %s' % (packageName))
                            pass
                        else:
                            funcName = '%s_%s' % (packageName,f.__name__)
                            CPEM_Server.register_function(f,funcName)
                except(Exception,e2):
                    print('W: son, I am dissapoint. (%s)' % (e2[0]))
            except(Exception,e):
                print('W: found the module at %s, but could not import it. (%s)' % (filename,e[0]))
            #if f: f.close()  #dunno why this hoses things up, but it really does... 
        except(Exception,e3):
            print('W: failed to load the "%s" plugin (%s%s), skipping it! (Python says, "%s")' % (packageName,path,packageName,e3[0]))


def refresh_plugins(CPEM_Server,path='%s/plugins/' % (os.getcwd()),pluginName=''):
    """refresh_plugins()
    handles re-loading plugins, on-demand, either reloading all plugins or reloading only specified plugins
    """
    #TODO: re-run their init() routines
    pass
